package com.shenmou.petwater.android.widget;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shenmou.petwater.android.Device;
import com.shenmou.petwater.android.R;
import com.shenmou.petwater.android.adapter.MyViewPageAdapter;
import com.shenmou.petwater.android.base.AppConfig;
import com.shenmou.petwater.android.base.BaseActivity;
import com.shenmou.petwater.android.utils.SPUtil;
import com.shenmou.petwater.android.view.DynamicWave;
import com.shenmou.petwater.android.view.DynamicWaveMenu;
import com.shenmou.petwater.android.view.WaterInfoView;
import com.xiaomi.smarthome.device.api.BaseDevice;
import com.xiaomi.smarthome.device.api.BaseDevice.StateChangedListener;
import com.xiaomi.smarthome.device.api.Callback;
import com.xiaomi.smarthome.device.api.DeviceUpdateInfo;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements StateChangedListener{
    static final int MSG_UPDATE_FIRM = 1;
    private static final String TAG = "首页";
    private Device mDevice;
    private View mNewFirmView;
    private TextView mTitleView;
    private DynamicWave dynamicWave;
    private DynamicWaveMenu dynamicWaveMenu;
    private RelativeLayout rlMenu;
    private ViewPager viewPager;
    //1,定义GestureDetector类
    private GestureDetector m_gestureDetector;
    private TextView mMainTvWorkTime;
    private TextView mMainCurrentTemperature;
    private static SPUtil spUtil;
    private ImageView ivWaterSwitch;
    private ImageView ivLightSwitch;
    // true 运行  false 暂停
    private boolean run = true;
    //true 开灯  false  关灯
    private boolean light = true;

    public static SPUtil getSpUtil() {
        return spUtil;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spUtil = SPUtil.getInstance(MainActivity.this,"shenm_pet_water");
        //2,初始化手势类，同时设置手势监听
        m_gestureDetector = new GestureDetector(MainActivity.this, onGestureListener);
        initViewPage();
        initView();
    }



    private WaterInfoView wivWaterQuality;//水质
    private WaterInfoView wivDrinkingWater;//饮水量
    private List<View> views = new ArrayList<>();
    private  View view1;
    private View view2;
    private static MyViewPageAdapter myViewPageAdapter;


    private void initViewPage() {
        viewPager = (ViewPager) findViewById(R.id.top_viewPage);
        view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.viewpage_layout_drinking_water,null,false);
        wivDrinkingWater = view1.findViewById(R.id.wiv_drinking_water);
        wivDrinkingWater.setDrinkingWater(true);
        wivDrinkingWater.setValueTag(getString(R.string.string_main_tag_drinking_water_unit));
        wivDrinkingWater.setmTopTitle(getString(R.string.string_main_tag_drinking_water));
        wivDrinkingWater.setDrawBottomStatusBg(false);
        view2 = LayoutInflater.from(MainActivity.this).inflate(R.layout.viewpage_layout_water_quality,null,false);
        wivWaterQuality = view2.findViewById(R.id.wiv_water_quality);
        wivWaterQuality.setDrinkingWater(false);
        wivWaterQuality.setValueTag(getString(R.string.string_main_tag_water_quality_unit));
        wivWaterQuality.setmTopTitle(getString(R.string.string_main_tag_water_quality));
        views.add(view1);
        views.add(view2);
        myViewPageAdapter = new MyViewPageAdapter(views);
        viewPager.setAdapter(myViewPageAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        ivWaterSwitch = (ImageView)findViewById(R.id.water_switch);
        mMainTvWorkTime = (TextView) findViewById(R.id.main_tv_working_time);
        mMainCurrentTemperature = (TextView)findViewById(R.id. main_tv_water_temperature);
        mNewFirmView = findViewById(R.id.title_bar_redpoint);
        mTitleView = ((TextView) findViewById(R.id.title_bar_title));
        mTitleView.setText(getString(R.string.string_main_title));
        // 初始化device
        mDevice = Device.getDevice(mDeviceStat);

        // 设置titlebar在顶部透明显示时的顶部padding
        mHostActivity.setTitleBarPadding(findViewById(R.id.title_bar));
        ivWaterSwitch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(run){
                    run = false;
                    dynamicWave.setRunning(false);
                    dynamicWaveMenu.setRunning(false);
                    ivWaterSwitch.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,R.drawable.close));
                }else {
                    run = true;
                    dynamicWave.setRunning(true);
                    dynamicWaveMenu.setRunning(true);
                    ivWaterSwitch.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,R.drawable.open));
                }

            }
        });
        ivLightSwitch = (ImageView)findViewById(R.id.light_switch);
        ivLightSwitch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(light){
                    light = false;
                    dynamicWave.setAlpha(0.3f);
                    dynamicWaveMenu.setAlpha(0.3f);
                    ivLightSwitch.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,R.drawable.light_close));
                }else {
                    light = true;
                    dynamicWaveMenu.setAlpha(1f);
                    dynamicWave.setAlpha(1f);
                    ivLightSwitch.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,R.drawable.light_open));
                }
            }
        });
        findViewById(R.id.title_bar_return).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.title_bar_more).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mHostActivity.openMoreMenu(null, true, -1);
            }
        });

        // 打开分享
        View shareView = findViewById(R.id.title_bar_share);
        if (mDevice.isOwner()) {
            shareView.setVisibility(View.VISIBLE);
            shareView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mHostActivity.openShareActivity();
                }
            });
        } else {
            shareView.setVisibility(View.GONE);
        }
        dynamicWave = (DynamicWave) findViewById(R.id.dynamicWave);
        dynamicWaveMenu = (DynamicWaveMenu)findViewById(R.id.dynamicWaveMenu);
        rlMenu = (RelativeLayout) findViewById(R.id.rl_menu_content);
        dynamicWave.setTouchListener(new DynamicWave.DynamicWaveTouchListener() {
            @Override
            public void touchUp() {
//                toastMsg("向上滑动");
                showOrGoneView(true);
            }

            @Override
            public void touchDown() {

            }
        });
        rlMenu.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                 m_gestureDetector.onTouchEvent(event);
                return true;
            }
        });
        findViewById(R.id.include_main_work_time).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,WorkTimeSelectActivity.class);
                startActivity(intent,"com.shenmou.petwater.android.widget.WorkTimeSelectActivity");
            }
        });
        findViewById(R.id.include_main_rl_change_water).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,HintMsgActivity.class);
                intent.putExtra(AppConfig.INTENT_TYPE,AppConfig.INTENT_TYPE_CHANGE_WATER);
                startActivity(intent,"com.shenmou.petwater.android.widget.HintMsgActivity");
            }
        });
        findViewById(R.id.main_rl_filter_element).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,HintMsgActivity.class);
                intent.putExtra(AppConfig.INTENT_TYPE,AppConfig.INTENT_TYPE_FILTER_ELEMENT);
                startActivity(intent,"com.shenmou.petwater.android.widget.HintMsgActivity");
            }
        });
        findViewById(R.id.include_main_rl_submerged_pump).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,HintMsgActivity.class);
                intent.putExtra(AppConfig.INTENT_TYPE,AppConfig.INTENT_TYPE_SUBMERGED_PUMP);
                startActivity(intent,"com.shenmou.petwater.android.widget.HintMsgActivity");
            }
        });
        findViewById(R.id.include_main_water_intake).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,WaterIntakeDetailActivity.class);
                startActivity(intent,"com.shenmou.petwater.android.widget.WaterIntakeDetailActivity");
            }
        });
    }



    protected static final float FLIP_DISTANCE = 50;

    //初始化手势监听对象，使用GestureDetector.OnGestureListener的实现抽象类，因为实际开发中好多方法用不上
    private  GestureDetector.OnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if (e2.getY() - e1.getY() > FLIP_DISTANCE) {
                Log.i("MYTAG", "向下滑...");
                showOrGoneView(false);
                return true;
            }
            return super.onScroll(e1, e2, distanceX, distanceY);
        }



        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.d("GestureDemoView", "onFling() velocityX = " + velocityX);
            if (e1.getX() - e2.getX() > FLIP_DISTANCE) {
                Log.i("MYTAG", "向左滑...");
                return true;
            }
            if (e2.getX() - e1.getX() > FLIP_DISTANCE) {
                Log.i("MYTAG", "向右滑...");
                return true;
            }
            if (e1.getY() - e2.getY() > FLIP_DISTANCE) {
                //向上滑
               
                return true;
            }
            if (e2.getY() - e1.getY() > FLIP_DISTANCE) {
                Log.i("MYTAG", "向下滑...");
                showOrGoneView(false);
                return true;
            }
            Log.d("TAG", e2.getX() + " " + e2.getY());
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    };

    public void refreshUI() {
//        mTitleView.setText(mDevice.getName());
        mMainTvWorkTime.setText(spUtil.getString(AppConfig.SHARED_WORK_TIME,"请设置"));
        if(mDeviceStat.isOnline){
            //设备在线
            wivDrinkingWater.setBottomTag(getString(R.string.device_string_on_line));
        }else {
            //设备离线
            wivDrinkingWater.setBottomTag(getString(R.string.device_string_equipment_offline));
        }
        Log.d(TAG, "refreshUI: "+mDeviceStat.propInfo.toString());

    }

    @Override
    public void onResume() {
        super.onResume();

        // 检测是否有固件更新
        mDevice.checkDeviceUpdateInfo(new Callback<DeviceUpdateInfo>() {

            @Override
            public void onSuccess(DeviceUpdateInfo updateInfo) {
                Message.obtain(mHandler, MSG_UPDATE_FIRM, updateInfo).sendToTarget();
            }

            @Override
            public void onFailure(int arg0, String arg1) {

            }
        });
        mDevice.updateDeviceStatus();
//        ((TextView) findViewById(R.id.title_bar_title)).setText(mDevice.getName());

        // 监听设备数据变化
        mDevice.addStateChangedListener(this);
        refreshUI();
    }


    @Override
    public void onPause() {
        super.onPause();

        // 取消监听
        mDevice.removeStateChangedListener(this);

    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_UPDATE_FIRM:
                // 刷新固件升级状态
                DeviceUpdateInfo updateInfo = (DeviceUpdateInfo) msg.obj;
                if (updateInfo.mHasNewFirmware) {
                    mNewFirmView.setVisibility(View.VISIBLE);
                } else {
                    mNewFirmView.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onStateChanged(BaseDevice device) {
        refreshUI();
    }


    /**
     * 控制显示或者隐藏
     * @param water
     */
    private void showOrGoneView(boolean water){
        if(water){
            //菜单
            dynamicWave.setVisibility(View.GONE);
            rlMenu.setVisibility(View.VISIBLE);
        }else {
            rlMenu.setVisibility(View.GONE);
            dynamicWave.setVisibility(View.VISIBLE);
        }
    }





}

